﻿using DA.AnimGraph;
using OdinSerializer;
using System.Collections.Generic;
using System.Linq;

namespace DA.AnimGraph.Editor {
    internal class AGANode_StateMachine : AGANode_BlendBase {

        public override AGANodeModelBase modelProperty { set => model = (AGANodeModel_StateMachine)value; get => model; }
        [OdinSerialize] AGANodeModel_StateMachine model;
        public AGANode_StateMachine(AGANodeModelBase model) : base(model) {
            inputChildren.Add(AUIDGenerator.Gen());
            inputNames.Add("state 0");
            inputChildren.Add(AUIDGenerator.Gen());
            inputNames.Add("state 1");
        }
        public override int Publish(List<PublishNode> outNodes, AGAPublisher.PublishContext context) {
            var pNode = new StateMachinePNode();
            pNode.uuid = uuid;
            pNode.data = model.Publish(context, this);
            var index = outNodes.Count;
            outNodes.Add(pNode);

            pNode.inputChildren = new int[inputChildren.Count];
            for (int i = 0; i < inputChildren.Count; i++) {
                var childUuid = inputChildren[i];
                var childNode = context.subGraph.FindNextNodeInstance(uuid, childUuid) as AGANode_FunctionBase;
                if (childNode != null) pNode.inputChildren[i] = AGAPublisher.ExportNode(childNode, outNodes, context);
                else pNode.inputChildren[i] = -1;
            }

            PublishPerks(pNode, context);
            return index;
        }
    }

    [ModelOf(typeof(AGANode_StateMachine))]
    internal class AGANodeModel_StateMachine : AGANodeModelBase {

        public AGAFieldModel_IntLink defaultState = new();
        public List<AGAFieldModel_SMTransition> transitions = new();

        public StateMachineNode.SetupData Publish(AGAPublisher.PublishContext context, AGANode_StateMachine agaNode) {
            var result = new StateMachineNode.SetupData() {
                defaultStateIndex = defaultState.Publish(context),
                transitionsDesc = transitions.Select(t => t.Publish(context, agaNode)).ToArray(),
            };
            return result;
        }
    }
}
